package com.novunda.license.core;

import com.novunda.license.sm2.Sm2LoadSigleton;

import java.util.regex.Pattern;

/**
 * @author linfeng
 * @since 2016/10/12.
 */
final class SM2Decode implements LicenseDecode {

    private static final Pattern PATTERN = Pattern.compile(" ");
    private final String privateKey;

    public SM2Decode(String privateKey) {
        this.privateKey = privateKey;
    }

    public String getPrivateKey() {
        return privateKey;
    }

    @Override
    public LicenseContent decode(String content) throws LicenseException {

        String cipherText1 = PATTERN.matcher(content).replaceAll("+");
        byte[] cipherTextDecode = Base58.decode(cipherText1);

        byte[] deviceInforDecrypt = Sm2LoadSigleton.INSTANCE.special_decrypt(privateKey, cipherTextDecode);
        if (deviceInforDecrypt == null) {
            throw new LicenseException("解密失败");
        }
        return (LicenseContent) PersistenceService.load(deviceInforDecrypt);
    }


}
